package com.zed.api.common.adpt;

import java.util.List;

/**
 * 适配工具
 *
 * @author Zed
 */
public abstract class AdaptObjectUtils {

    private static volatile AdaptObjectFactoryRepository INSTANCE;

    /**
     * 通过AdaptObjectFactoryRepository查找定位适配对象
     *
     * @param <T>
     * @param <R>
     * @param hostType  {@link Class},宿主类型
     * @param adaptType {@link Class},适配类型
     * @param host      {@link Object},宿主实例
     * @return {@link R}
     */
    public static <T, R> R getAdaptObject(Class<T> hostType, Class<R> adaptType, T host) {
        if (INSTANCE == null) return null;

        List<AdaptObjectFactory<R>> factories =
                INSTANCE.getAdaptObjectFactories(adaptType, hostType);
        for (AdaptObjectFactory<R> factory : factories) {
            R result = factory.createAdaptObject(host, adaptType);
            if (result != null) {
                return result;
            }
        }

        return null;
    }

    /**
     * 绑定适配对象
     *
     * @param value {@link AdaptObjectFactoryRepository}
     */
    public static boolean bind(AdaptObjectFactoryRepository value) {
        if (INSTANCE == null) {
            INSTANCE = value;
            return true;
        }
        return false;
    }
}
